package com.example.infrastructure.framework.interceptor;

import com.example.common.core.domain.entity.SysUser;
import com.example.common.core.domain.model.LoginUser;
import com.example.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;


@Slf4j
@Component
public class MultiAuthenticationFilter extends OncePerRequestFilter {

    // 注意过滤器中不能使用@Resource，使用@Autowired,否则外置服务器启动时会报错

    /** 鉴权方式 */
    @Value("${auth.type}")
    private String authType;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        
        boolean isAuthentication = StringUtils.isNotEmpty(authType);
        
        log.info("拦截器接收请求【{}】，是否鉴权【{}】，鉴权方式【{}】", request.getRequestURI(), isAuthentication, authType);
        
        LoginUser loginUser = null;
        if (isAuthentication) {
            // TODO 鉴权
            switch (authType){
                case "token":break;
                case "aksk":break;
                case "session":break;
                default: break;
            }
        }else {
            // 默认用户登录
            loginUser = generateDefaultLoginUser();
        }

        try {
            System.out.println("start");
            // response.getWriter().println("Some content");
            // request.getSession(); // 这会抛出异常
        }catch (Exception e){
            log.error("error",e);
        }
        
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);

    }

    /**
     * 生成默认用户
     * @return
     */
    public LoginUser generateDefaultLoginUser() {

        SysUser sysUser = new SysUser();
        sysUser.setUserName("admin");
        sysUser.setPassword("dwa*%^75e413143!@#@!$232da");
        
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(1111111111L);
        loginUser.setPermissions(new HashSet<String>(){{
            add("*:*:*");
        }});
        loginUser.setUser(new SysUser());
        
        return loginUser;
    }
    


}
